﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using BingVis.SilverlightClient.GoogleTransit;
using System.Windows.Media;

namespace BingVis.SilverlightClient
{
    /// <summary>
    /// Quick and dirty color converter...
    /// </summary>
    public static class ColorConverter
    {
        private const byte a = 255; // Always full alpha
        public static Color ConvertFromString(string col)
        {
            //var cleaned = new String(col.Trim(" #".ToCharArray()).ToCharArray().Skip(col.Length - 6).Take(6).ToArray());
            var cleaned = col.Trim(" #".ToCharArray());

            if (cleaned.Length < 6)
                return Colors.Gray;                

            // Skip the alpha if present...
            int startIdx = cleaned.Length > 6 ? 2 : 0;

            byte r, g, b;
            
            r = (byte)(Convert.ToUInt32(cleaned.Substring(startIdx, 2), 16));
            g = (byte)(Convert.ToUInt32(cleaned.Substring(startIdx + 2, 2), 16));
            b = (byte)(Convert.ToUInt32(cleaned.Substring(startIdx + 4, 2), 16));

            return Color.FromArgb(a, r, g, b);
        }
    }

    public class StopNameToColorConverter : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var stopName = value as string;
            stopName = StopNameLookup.GetStopName(stopName);

            var colors = StopColorLookup.GetStopColors(stopName);

            if (colors.Count < 1)
                return new SolidColorBrush(Colors.White);
                        
            var col = ColorConverter.ConvertFromString(colors[0]);

            return new SolidColorBrush(col);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
